package com;

import java.util.Comparator;

public class BinarySearch {
	public static <T extends Comparable<T>> int binarySearch(T[] a, T x,
			Comparator<T> comparator) {
		if (a == null) {
			throw new IllegalArgumentException("被查找数组为null！");
		} else if (x == null) {
			throw new IllegalArgumentException("被查询元素为null！");
		}

		int left = 0;
		int right = a.length - 1;

		while (left <= right) {
			int middle = (left + right) / 2;
			if (comparator != null) {
				if (comparator.compare(x, a[middle]) == 0)
					return middle;
				if (comparator.compare(x, a[middle]) > 0)
					left = middle + 1;
				else
					right = middle - 1;
			}

			else {
				if (x.compareTo(a[middle]) == 0)
					return middle;
				if (x.compareTo(a[middle]) > 0)
					left = middle + 1;
				else
					right = middle - 1;
			}

		}
		return -1;
	}

	public static void main(String[] args) {
		Student[] a = new Student[4];
		a[0] = (new Student(3, "Tom"));
		a[1] = (new Student(5, "John"));
		a[2] = (new Student(7, "David"));
		a[3] = (new Student(9, "Alice"));

		Student x = new Student(7, "John");// 设定要查找的数

		int position = binarySearch(a, x, new StudentComparator());
		System.out.println(x + "在数组中的位置是" + position);

	}
}
